package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IcheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 老人入住信息Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class checkInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements IcheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询老人入住信息
     * 
     * @param id 老人入住信息主键
     * @return 老人入住信息
     */
    @Override
    public CheckIn selectcheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人入住信息列表
     * 
     * @param checkIn 老人入住信息
     * @return 老人入住信息
     */
    @Override
    public List<CheckIn> selectcheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectcheckInList(checkIn);
    }

    /**
     * 新增老人入住信息
     * 
     * @param checkIn 老人入住信息
     * @return 结果
     */
    @Override
    public int insertcheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改老人入住信息
     * 
     * @param checkIn 老人入住信息
     * @return 结果
     */
    @Override
    public int updatecheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除老人入住信息
     * 
     * @param ids 需要删除的老人入住信息主键
     * @return 结果
     */
    @Override
    public int deletecheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人入住信息信息
     * 
     * @param id 老人入住信息主键
     * @return 结果
     */
    @Override
    public int deletecheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     */
    @Override
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已入住
        //通过身份证号查询老人信息
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderQueryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtil.isNotNull(elder)) {
            throw new RuntimeException("该老人已入住");
        }
        //更新床位状态为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增或更新老人信息
        elder = insertOrUpdateElder(bed,dto.getCheckInElderDto());

        //生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        //新增签约办理
        insertContract(contractNo, elder, dto);
        //新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);
        //新增入住配置信息
        insertCheckInContract(dto, elder);
    }

    private void insertCheckInContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setElderName(elder.getName());
        contract.setContractName(contract.getContractName());
        contract.setStartDate( dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(Long.valueOf(contract.getStartDate().isBefore(LocalDateTime.now())?1:0));
    }


    /**
     * 新增入住信息
     * @param elder
     * @param dto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = BeanUtil.copyProperties(dto.getCheckInElderDto(), CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setIdCard(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList().toString()));

        return checkIn;
    }

    @Autowired
    private ContractMapper contractMapper;
    /**
     * 新增签约办理
     *
     * @param contractNo
     * @param elder
     * @param dto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setElderName(elder.getName());
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     *
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        // 准备老人数据
        Elder elder = new Elder();
        // 属性拷贝
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        // 查询老人信息，（身份证号、状态不为1）
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb =  elderMapper.selectOne(lambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(elder);
        }else {
            // 新增
            elderMapper.insert(elder);
        }
        return elder;
    }
}
